﻿//注：本文件很多方法Lswweb.Controls中都用到，所以必须引入本文件


//仿阿里巴巴右则滑动快速导航
//调用方式：$("#slideTabs").SlideTabs();
//Theme代码：
//.slideTabs{border:1px solid #000;}
//.slideTabs .slideTabs-tab{border:1px solid #000;padding:5px;margin:5px;float:left;}
//.slideTabs .slideTabs-tab-show{border:1px solid red;}
//.slideTabs .slideTabs-tab-show-left{border-left:1px solid red;float:left;}
//.slideTabs .slideTabs-tab-show-right{border-right:1px solid red;float:left;}
//.slideTabs .slideTabs-panel{}
(function ($) {
    $.fn.SlideTabs = function (settingOptions) {
        liControls = this.find("li"), divControls = this.find("div"), ulControls = this.find("ul");
        var columns = liControls.length / ulControls.length;
        var settings = { className: "slideTabs", index: "0" }
        $.extend(true, settings, settingOptions);

        this.addClass(settings.className);

        liControls.each(function (index) {
            $(this).addClass("slideTabs-tab");
            if (index == settings.index) $(this).toggleClass("slideTabs-tab-show");
        }).mouseover(function () {
            var index = liControls.index($(this));
            if (settings.index != index) {
                liControls.filter("li:eq(" + settings.index + "),li:eq(" + index + ")").toggleClass("slideTabs-tab-show");
                divControls.filter("div:eq(" + settings.index + "),div:eq(" + index + ")").toggle();
                settings.index = index;
            }
        });

        divControls.each(function (index) {
            $(this).addClass("slideTabs-panel").css({ clear: "both" });
            if (index != settings.index) $(this).hide();
        });

        ulControls.each(function () {
            $(this).css({ display: "block", zoom: "1", clear: "both" });
        });
    }
})(jQuery);

//给控件选择配置不同的css样式
//$("control").CssChange({defaultClass:"class1",items[{controlId:"control1",className:"class1"},{controlId:"control2",className:"class2"}]});
(function ($) {
    $.fn.CssChange = function (settingOptions) {
        var settings = { defaultCss: "", items: [] }, self = this;
        $.extend(true, settings, settingOptions);

        if (!!settings.defaultCss)
            self.attr("class", settings.defaultCss);

        for (var i = 0; i < settings.items.length; i++) {
            var item = settings.items[i];
            if (!item || !item.controlId || !item.className) continue;

            $("#" + item.controlId).attr("setClass", item.className).click(function () {
                self.attr("class", $(this).attr("setClass"));
            });
        }
    }
})(jQuery);

//图片幻灯效果
//.slides{width: 408px;height: 168px;border:1px solid #000;list-style:none;}
//.slides ul{padding:0px;margin:0px; }
//.slides .slider li{padding:0px;margin:0px;height:168px;overflow:hidden;}
//.slides .number{position:absolute; right:5px;bottom:5px;}
//.slides .number li{border:1px solid #000;padding:0px 5px; background-color:#fff;float:left; margin-left:5px;}
//.slides .number .selected{background-color:Red; }
(function ($) {
    $.fn.Slides = function (settingOptions) {
        var self = this;
        this.settings =
        {
            Timer: null, //setTimeout事件
            Slider: this.find("ul:eq(0)"), //滑动对像
            Number: this.find("ul:eq(1)"), //导航按钮对像
            Index: 0, //当前对像索引
            Options: {
                Up: true, //是否向上(否则向左)
                Step: 5, //滑动变化率
                Time: 10, //滑动延时
                Auto: true, //是否自动转换
                Pause: 2000, //停顿时间(Auto为true时有效)
                Parameter: 0, //切换参数
                Count: this.find("ul:eq(0) li").length
            }
        }
        $.extend(true, this.settings.Options, settingOptions || {});

        if (!this[0] || !this.settings.Slider[0] || !this.settings.Number[0]) return;

        this.addClass("slides");
        this.css({ overflow: "hidden", position: "relative" });
        if (!this.settings.Options.Parameter) this.settings.Options.Parameter = this.settings.Options.Up ? parseInt(this.height()) : parseInt(this.width());

        this.settings.Slider.css({ position: "absolute", left: "0", top: "0" }).addClass("slider");
        this.settings.Number.addClass("number").find("li").each(function (i) {
            $(this).mouseover(function () {
                self.settings.Index = i;
                self.settings.Options.Auto = false;
                self.SetCurrentNumberClass();
                self.Move();
            }).mouseout(function () {
                self.settings.Options.Auto = !settingOptions ? true : settingOptions.Auto == null ? true : settingOptions.Auto;
                self.Move();
            });
        });

        this.extend({
            Move: function () {
                clearTimeout(this.settings.Timer);
                if (this.GetStep() != 0) {
                    this.timer = setTimeout(function () { self.Move(); }, this.settings.Time);
                }
                else {
                    if (self.settings.Options.Auto) {
                        this.settings.Timer = setTimeout(function () {
                            self.settings.Index = self.GetTargetIndex();
                            self.SetCurrentNumberClass();
                            self.Move();
                        }, this.settings.Options.Pause);
                    }
                }
                this.settings.Slider.css(this.settings.Options.Up ? "top" : "left", (this.GetNowPosition() + this.GetStep()) + "px");
            },

            GetStep: function () {
                var iStep = (this.GetTargetPosition() - this.GetNowPosition()) / this.settings.Options.Step;
                if (iStep == 0) return 0;
                if (Math.abs(iStep) < 1) iStep = (iStep > 0 ? 1 : -1);
                return iStep;
            },

            //获取目标位置
            GetTargetPosition: function () {
                return this.settings.Index * this.settings.Options.Parameter * -1;
            },

            //取得目标位置的索引
            GetTargetIndex: function () {
                if (this.settings.Index >= (this.settings.Options.Count - 1)) return 0;
                else return (this.settings.Index + 1);
            },

            SetCurrentNumberClass: function () {
                this.settings.Number.find("li").each(function (i) {
                    if (i == self.settings.Index)
                        $(this).addClass("selected");
                    else
                        $(this).removeClass("selected");
                })
            },

            //获取当前位置
            GetNowPosition: function () {
                return parseInt(this.settings.Slider.css(this.settings.Options.Up ? "top" : "left")) || 0;
            }
        });

        this.Move();
        this.SetCurrentNumberClass();
    }
})(jQuery);

(function ($) {  // 滚动插件代码
    $.fn.Scroll = function (options) {
        options = options || {};
        this.css('overflow', 'hidden');
        var scroll = (function (self) {
            return function () {
                if (self.data('scroll_stop')) {
                    return;
                }
                var li = self.find('li:first');
                var liMarginTop = parseInt(li.css('marginTop')) || 0;
                li.animate({
                    'marginTop': liMarginTop - li.outerHeight()
                }, options.speed || 'slow', function () {
                    self.append(li);
                    li.css('marginTop', liMarginTop);
                });
            };
        })(this);

        setInterval(scroll, options.delay || 2000);

        this.hover(function () {
            $(this).data('scroll_stop', true);
        }, function () {
            $(this).removeData('scroll_stop');
        });
    };
})(jQuery);

//可编辑DropDownList
//Add(value,text)给dropdownList添加一个新的listitem
//Remove() 移除当前选择的listItem
//Value(selected) selected为true时取得当前选择的item的value否则取得当前dropDownList所有Item的value集合
(function ($) {
    $.fn.EditDropDownList = function (settingOptions) {
        this.settings = {
            Max: 99, //最多可添加的item数量
            MaxMessage: "超过最大数量{0}。", //超过max数量时的提示信息
            ChangeClick: function () { }, //当add()和remove()后执行的方法。 可添加一个参数self，用来代表当前$("#Id").EditDropDownList(settingOptions);对像
            SelectClick: function () { }
        }

        this.extend({
            //取得值，多个item值之间用","隔开，如果selected参数为true则只返回当前选择项的value
            vals: function (selected) {
                if (selected) {
                    return this.find("option:selected").val();
                }

                var value;
                this.find("option").each(function () {
                    value += "," + $(this).val();
                });

                return value ? value.substring(1, value.length) : "";
            },
            //添加一条新选择项
            add: function (value, text) {
                if (!value && !text)
                    return;
                else if (!value && text)
                    value = text;
                else if (value && !text)
                    text = value;

                if (this.find("option").length >= this.settings.Max) {
                    alert(this.settings.MaxMessage.format(this.settings.Max));
                    return;
                }

                if (this.find("option[value=" + value + "]").length == 0) {
                    this.append("<option value=\"" + value + "\" selected>" + text + "</option>");
                    this.settings.ChangeClick(this.vals());
                }
            },
            //删除当前选择的项
            remove: function () {
                this.find("option:selected").remove();
                this.settings.ChangeClick(this.vals());
            }
        });


        $.extend(true, this.settings, settingOptions || {});

        var self = this;
        this.change(function () {
            self.settings.SelectClick(self.vals(true));
        });

        return this;
    }
})(jQuery);


//取消点时控件四周出现虚框
(function ($) {
    $.fn.AutoBlur = function () {
        this.focus(function () { this.blur(); });
    }
})(jQuery);

//添加鼠标移动到控件上样式
(function ($) {
    $.fn.MousemoveCss = function (selectedClassName) {
        if (!selectedClassName || selectedClassName.length <= 0) selectedClassName = "selected";

        this.mousemove(function () { $(this).addClass(selectedClassName); });
        this.mouseout(function () { $(this).removeClass(selectedClassName); });
    }
})(jQuery);

//表格内的 CheckBoxList 全选/全取消
//需要在tr上边加attr(identity=绑定记录标识Id)
(function ($) {
    $.fn.CheckBoxTable = function (settingOptions) {
        var self = this;
        var tableSettings = { //为不和$.checkBoxAll.settings重复
            checkClass: null
        }

        $.extend(true, tableSettings, settingOptions || {});

        this.find("tr").each(function (index) {
            $(this).prepend("<td style=\"width:25px;\"><input type=\"checkbox\" /></td>");
        });

        var checkBoxAll = this.find("tr input[type=checkbox]:eq(0)"); //全选/反选 按钮
        var checkList = this.find("tr[identity] input[type=checkbox]"); //所有checkbox 按钮列表
        var itemList = this.find("tr[identity]");

        checkBoxAll.click(function () {
            var checked = $(this).attr("checked");

            checkList.each(function (index) {
                if ($(this).attr("checked") == checked) return;

                $(this).attr("checked", checked);

                if (checked)
                    $(itemList[index]).addClass(tableSettings.checkClass);
                else
                    $(itemList[index]).removeClass(tableSettings.checkClass);

            });
        })

        itemList.hover(function () {
            //鼠标移动到的当前行，添加class=selected
            $(this).addClass(tableSettings.checkClass);
        }, function () {
            //鼠标离开的当前行，移除class=selected
            if (!$(this).find("input[type=checkbox]").attr("checked")) $(this).removeClass(tableSettings.checkClass);
        }).click(function () {
            $(this).find("input[type=checkbox]").attr("checked", !$(this).find("input[type=checkbox]").attr("checked"));
        }).find("a,input").click(function (event) { //阻止事件冒泡
            var eve = event || window.event;
            eve.stopPropagation();
        });

        //单行记录操作模板
        function ItemHandler(event) {
            if (event.data.confirm && event.data.confirm.length > 0) {
                if (!confirm(event.data.confirm)) return;
            }
            var identity = self.getIdentity($.inArray(this, event.data.items))
            var returnObj = event.data.ajaxFun.call(this, identity, this);
            if (returnObj.Type == 24) {
                self.removeSelected(identity);

                if (event.data.success) event.data.success.call(this, this);

                if (event.data.isRemoveItem) self.removeRow(identity);
            }
//            $.Message(returnObj.Title, returnObj.Body);
        }

        //批量记录操作模板
        function BatchHandler(event) {
            if (event.data.confirm && event.data.confirm.length > 0) {
                if (!confirm(event.data.confirm)) return;
            }
  
            var vals = self.vals();
            var s = 0; e = 0;
            var batch = this;
            $.each(vals, function (i, n) {
                var index = $.inArray(n, checkList);
                var identity = self.getIdentity(index);
                var returnObj = event.data.ajaxFun.call(this, identity, batch);
                if (returnObj.Type == 24) {
                    self.removeSelected(identity);

                    if (event.data.success) event.data.success.call(this, batch, index); //两个参数，分别是批量控件，和当前处理列索引

                    if (event.data.isRemoveItem) self.removeRow(identity);

                    s++;
                }
                else {
                    e++;
                }
            })
            checkBoxAll[0].checked = false;
//            $.Message(event.data.messageTitle, event.data.messageBody.format(s, e));
        }

        this.extend({
            removeRow: function (identity) {
                var row = this.find("tr:[identity=" + identity + "]");
                var index = $.inArray(row[0], itemList);
                checkList.splice(index, 1);
                itemList.splice(index, 1);
                row.remove();
            },
            removeSelected: function (identity) {
                var row = this.find("tr:[identity=" + identity + "]");
                row.removeClass(tableSettings.checkClass);
                row.find("input[type=checkbox]").attr("checked", false);
            }
            ,
            getIdentity: function (index) {
                return $(itemList[index]).attr("identity");
            }
            ,
            vals: function () {
                return $.grep(checkList, function (n, i) { return n.checked == true; });
            }
            ,
            bindDel: function (delSettings) {
                var settings = {
                    formatUrl: null,
                    ajaxType: null,
                    isPhysics: false,
                    isRemoveItem: true, //是否删除当前操作完成的行
                    confirmMessage: "确定要删除当前记录吗？删除后将不可恢复！",
                    itemButtonExpr: "a:[title=delete]",
                    batchEndMessageTitle: "批量删除结束",
                    batchEndMessageBody: "成功删除记录条数{0}条，失败{1}条！",
                    batchButtonExpr: "input[title=batchDel]"
                }

                $.extend(true, settings, delSettings || {});
                settings.isRemoveItem = Convert.ToBoolean(settings.isRemoveItem);
                settings.isPhysics = Convert.ToBoolean(settings.isPhysics);

                var delItems = $(settings.itemButtonExpr);
                var batch = $(settings.batchButtonExpr);

                function AjaxDelete(identity, obj) {
                    return $.ajaxJSON(settings.formatUrl.format(settings.ajaxType, identity, settings.isPhysics));
                }

                var confirmMessage = settings.isPhysics ? settings.confirmMessage : "";

                delItems.bind("click", { ajaxFun: AjaxDelete, items: delItems, confirm: confirmMessage, isRemoveItem: settings.isRemoveItem }, ItemHandler);

                batch.bind("click", { ajaxFun: AjaxDelete, messageTitle: settings.batchEndMessageTitle, messageBody: settings.batchEndMessageBody, confirm: confirmMessage, isRemoveItem: settings.isRemoveItem }, BatchHandler);
            }
            ,
            bindUpdateStatus: function (statusSettings) {
                var settings = {
                    formatUrl: "",
                    ajaxType: null,
                    toStatus: null,
                    isRemoveItem: true, //是否删除当前操作完成的行
                    itemButtonExpr: "a:[title=status]",
                    batchEndMessageTitle: "批量操作结束",
                    batchEndMessageBody: "操作成功{0}条记录，失败{1}条记录。",
                    batchButtonExpr: "input[title=batchStatus]"
                }

                $.extend(true, settings, statusSettings || {});
                settings.isRemoveItem = Convert.ToBoolean(settings.isRemoveItem);


                var statusItems = $(settings.itemButtonExpr);
                var batch = $(settings.batchButtonExpr);

                function AjaxUpdateStatus(identity, obj) {
                    return $.ajaxJSON(settings.formatUrl.format(settings.ajaxType, identity, settings.toStatus));
                }

                statusItems.bind("click", { ajaxFun: AjaxUpdateStatus, items: statusItems, isRemoveItem: settings.isRemoveItem }, ItemHandler);

                batch.bind("click", { ajaxFun: AjaxUpdateStatus, messageTitle: settings.batchEndMessageTitle, messageBody: settings.batchEndMessageBody, isRemoveItem: settings.isRemoveItem }, BatchHandler);
            },
            bindUpdateBoolean: function (booleanSettings) {
                var settings = {
                    formatUrl: "",
                    ajaxType: null,
                    toValAttr: "toVal",
                    trueText: "true", //当选择项的值为true
                    falseText: "false", //当值为false
                    isRemoveItem: true, //是否删除当前操作完成的行
                    itemButtonExpr: "a:[title=UpdateBoolean]",
                    batchEndMessageTitle: "批量操作结束",
                    batchEndMessageBody: "操作成功{0}条记录，失败{1}条记录。",
                    batchButtonExpr: "input[title=batchBoolean]"
                }

                $.extend(true, settings, booleanSettings || {});
                settings.isRemoveItem = Convert.ToBoolean(settings.isRemoveItem);

                var booleanItems = $(settings.itemButtonExpr);
                var batch = $(settings.batchButtonExpr);

                function AjaxUpdateBoolean(identity, obj) {
                    var toVal = Convert.ToBoolean($(obj).attr(settings.toValAttr));
                    return $.ajaxJSON(settings.formatUrl.format(settings.ajaxType, identity, toVal));
                }

                function ItemSuccess(obj) {
                    SetItem(Convert.ToBoolean($(obj).attr(settings.toValAttr)), obj);
                }

                function BatchItemSuccess(batchOjb, itemIndex) {
                    SetItem(Convert.ToBoolean($(batchOjb).attr(settings.toValAttr)), booleanItems[itemIndex]);
                }

                function SetItem(toVal, obj) {
                    var toStr = toVal ? settings.trueText : settings.falseText;
                    $(obj).text(toStr).attr(settings.toValAttr, !toVal);
                }

                booleanItems.each(function () {
                    var toStr = Convert.ToBoolean($(this).attr(settings.toValAttr)) ? settings.falseText : settings.trueText;
                    $(this).text(toStr);
                });

                booleanItems.bind("click", { ajaxFun: AjaxUpdateBoolean, items: booleanItems, success: ItemSuccess, isRemoveItem: settings.isRemoveItem }, ItemHandler);

                batch.bind("click", { ajaxFun: AjaxUpdateBoolean, items: booleanItems, success: BatchItemSuccess, messageTitle: settings.batchEndMessageTitle, messageBody: settings.batchEndMessageBody, isRemoveItem: settings.isRemoveItem }, BatchHandler);
            },
            bindRepublish: function (resetSettings) {
                var settings = {
                    formatUrl: "",
                    isRemoveItem: true, //是否删除当前操作完成的行
                    itemButtonExpr: "a:[title=republish]",
                    batchEndMessageTitle: "批量操作结束",
                    batchEndMessageBody: "操作成功{0}条记录，失败{1}条记录。",
                    batchButtonExpr: "input[title=batchRepublish]"
                }

                $.extend(true, settings, resetSettings || {});
                settings.isRemoveItem = Convert.ToBoolean(settings.isRemoveItem);

                var resetItems = $(settings.itemButtonExpr);
                var batch = $(settings.batchButtonExpr);

                function AjaxRepublish(identity, obj) {             
                    return $.ajaxJSON(settings.formatUrl.format(identity));
                }

                resetItems.bind("click", { ajaxFun: AjaxRepublish, items: resetItems, isRemoveItem: settings.isRemoveItem }, ItemHandler);

                batch.bind("click", { ajaxFun: AjaxRepublish, messageTitle: settings.batchEndMessageTitle, messageBody: settings.batchEndMessageBody, isRemoveItem: settings.isRemoveItem }, BatchHandler);
            }
        });

        return this;
    }
})(jQuery);

//ToolTips 浮动提示框
(function ($) {
    $.fn.ToolTips = function (settingOptions) {
        var self = this;
        var constructor;
        this.settings = {
            event: "mouse", // mouse、focus
            left: 0,
            top: 0,
            theme: "toolTips",
            tipId: "tip",
            position: "down" //down、right
        }

        $.extend(true, this.settings, settingOptions || {});

        var tip = $("#" + this.settings.tipId);

        this.extend({
            left: function () {
                var width = $(document).width();
                if (self.settings.position == "down") {
                    if (width - self.offset().left - self.settings.left - tip.outerWidth() > 0)
                        return self.offset().left + self.settings.left;
                    else
                        return self.offset().left - self.settings.left + this.outerWidth() - tip.outerWidth();
                }
                else {
                    if (width - self.offset().left - self.settings.left - tip.outerWidth() - this.outerWidth() > 0)
                        return self.offset().left + self.settings.left + this.outerWidth();
                    else
                        return self.offset().left - self.settings.left - tip.outerWidth();
                }
            },
            top: function () {
                var top = self.offset().top + self.settings.top;
                if (self.settings.position == "down") top += this.outerHeight();
                return top;
            },
            tipHide: function () {
                self.constructor = setTimeout(function () { tip.hide(); tip.attr("relatingId", ""); }, 200);
            },
            tipShow: function () {
                tip.show();
                tip.css({ left: self.left(), top: self.top() });
                tip.attr("relatingId", this[0].id);
            }
        });

        tip.css({ position: "absolute", display: "none" });

        tip.mousemove(function () {
            if (tip.attr("relatingId") != self[0].id) return;

            if (self.constructor) clearTimeout(self.constructor);
        })

        tip.mouseout(function () {
            if (tip.attr("relatingId") != self[0].id) return;

            self.settings.event == "mouse" ? self.tipHide() : self.focus();
        });

        this.bind(this.settings.event == "mouse" ? "mouseout" : "blur", function () {
            self.tipHide();
        });

        this.bind(this.settings.event == "mouse" ? "mouseover" : "focus", function () {
            self.tipShow();
        });
    }
})(jQuery);

(function ($) {
    $.fn.Resize = function (settingOptions) {
        var self = this;
        this.settings = {
            reduceWidth: 0,
            reduceHeight: 0,
            orientationMode: "All", //All、Height、Width 
            referToControlId: ""
        }

        $.extend(true, this.settings, settingOptions || {});

        var referToControl = !this.settings.referToControlId ? $(window) : $("#" + this.settings.referToControlId);

        $(window).resize(function () {
            var width = referToControl.width() - self.settings.reduceWidth - Convert.ToInt32(self.css("border-left-width")) - Convert.ToInt32(self.css("border-right-width")) - Convert.ToInt32(self.css("padding-left")) - Convert.ToInt32(self.css("padding-right")) - Convert.ToInt32(self.css("margin-left")) - Convert.ToInt32(self.css("margin-right"));
            var height = referToControl.height() - self.settings.reduceHeight - Convert.ToInt32(self.css("border-top-width")) - Convert.ToInt32(self.css("border-bottom-width")) - Convert.ToInt32(self.css("padding-top")) - Convert.ToInt32(self.css("padding-bottom")) - Convert.ToInt32(self.css("margin-top")) - Convert.ToInt32(self.css("margin-bottom"));

            if (self.settings.orientationMode == 'All')
                self.height(height).width(width);
            else if (self.settings.orientationMode == 'Width')
                self.width(width);
            else if (self.settings.orientationMode == 'Height')
                self.height(height);
        });

        $(window).resize();
    }
})(jQuery);

$.Message = function (titleHtml, contentHtml, returnUrl) {
    var message = $("#messageDialog");
    if (message[0]) {
        message.remove();
    }
    message = $("<div id=\"messageDialog\" style=\"width:300px;border:1px solid #000;background-color:#fff;padding:10px;\"></div>");

    if (titleHtml && titleHtml.length > 0) 
        message.append("<h2 class='title'>" + titleHtml + "</h2>");

    if (contentHtml && contentHtml.length > 0) 
        message.append("<p class='content'>" +  contentHtml + "</p>");

    message.append("<p><button class=\"close\">Close</button></p>");

    $("body").append(message);

    var overflow = $("html").css("overflow-y");


    message.overlay({ 
        closeOnClick: false,
        onBeforeLoad:function(){
            $("html").css("overflow-y", "hidden");
        },
        onClose:function(){
            if (returnUrl && returnUrl.length > 0) document.location.href = returnUrl;
            $("html").css("overflow-y", overflow);
            message.remove();
        },
        mask: {
		    color: '#ccc',
		    loadSpeed: 200,
		    opacity: 0.5
	    },
        load: true,
        top:150
    });

    message.click();
}

//Ajax方式访问WebServices
//例：$.webService({url: "/WebServices/WebService.asmx/GetWeather",data: "{ cityCode:\"440301\" }",success: function(msg) { alert(msg.d); }});
//GetWeather是WebServices服务名称，注意它后边不能带“/”。
//参数data:"{parameterName:1}"，参数名parameterName必须和webserivce中的参数名一至
//数组参数的写法data:"{parameterName:[1,2,3,4]}"
$.ajaxWebService = function (controlOptions) {
    var settings =
    {
        url: "",
        success: function (msg) { },
        data: "{}",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }
    controlOptions = controlOptions || {};
    $.extend(true, settings, controlOptions);

    return $.ajax(settings);
}

$.ajaxJSON = function (urlStr) {
    var label = false;
    $.ajax({ async: false, url: encodeURI(urlStr), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) {
        label = data;
    }
    });
    return label;
}

///转换
Convert = function () { };
Convert.ToInt32 = function (strNum) {
    var label = parseInt(strNum);
    if (isNaN(label))
        label = 0;
    return label;
}

Convert.ToBoolean = function (strBool) {
    if (strBool.toString().toLowerCase() == "true" || strBool.toString().toLowerCase() == "1")
        return true;
    else
        return false;
}

//字符串，添加format方法 使用方法 var a="1213{0},fdsfdsf{1}";a.format("1","2");
String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) { return args[i]; }
    );
}

function ImagePreviewClick(obj) {
    $.blockUI({ css: { padding: 15 }, message: '<p><img src=' + $(obj).attr('PreviewUrl') + ' /></p><input id=closeAlertMessage type=button value=关闭 />' }); $('#closeAlertMessage').click(function () { $.unblockUI(); });
}


//初始化
$(function () {
    //inputTable配置主题
    $("table[summary=InputTable]").each(function () {
        var cells = parseInt($(this).attr("cells"))
        if (!cells) cells = 2;
        $(this).find(' > tbody > tr > td:not([title=not])').each(function (i) {
            if (i % cells == 0) $(this).attr("class", "title");
        });
    })

    //取消点击连接时连接字符四周出现虚框
    $("a").AutoBlur();
});

function GetCityCode(cityName) {

    var citys = [{ Code: "110100", Name: "北京" }, { Code: "120100", Name: "天津" }, { Code: "130101", Name: "石家庄" }, { Code: "130201", Name: "唐山" }, { Code: "130301", Name: "秦皇岛" }, { Code: "130701", Name: "张家口" }, { Code: "130801", Name: "承德" }, { Code: "131001", Name: "廊坊" }, { Code: "130401", Name: "邯郸" }, { Code: "130501", Name: "邢台" }, { Code: "130601", Name: "保定" }, { Code: "130901", Name: "沧州" }, { Code: "133001", Name: "衡水" }, { Code: "140101", Name: "太原" }, { Code: "140201", Name: "大同" }, { Code: "140301", Name: "阳泉" }, { Code: "140501", Name: "晋城" }, { Code: "140601", Name: "朔州" }, { Code: "142201", Name: "忻州" }, { Code: "142331", Name: "离石" }, { Code: "142401", Name: "榆次" }, { Code: "142601", Name: "临汾" }, { Code: "142701", Name: "运城" }, { Code: "140401", Name: "长治" }, { Code: "150101", Name: "呼和浩特" }, { Code: "150201", Name: "包头" }, { Code: "150301", Name: "乌海" }, { Code: "152601", Name: "集宁" }, { Code: "152701", Name: "巴彦浩特" }, { Code: "152801", Name: "临河" }, { Code: "152921", Name: "鄂尔多斯" }, { Code: "150401", Name: "赤峰" }, { Code: "152301", Name: "通辽" }, { Code: "152502", Name: "锡林浩特" }, { Code: "152101", Name: "海拉尔" }, { Code: "152201", Name: "乌兰浩特" }, { Code: "210101", Name: "沈阳" }, { Code: "210201", Name: "大连" }, { Code: "210301", Name: "鞍山" }, { Code: "210401", Name: "抚顺" }, { Code: "210501", Name: "本溪" }, { Code: "210701", Name: "锦州" }, { Code: "210801", Name: "营口" }, { Code: "210901", Name: "阜新" }, { Code: "211101", Name: "盘锦" }, { Code: "211201", Name: "铁岭" }, { Code: "211301", Name: "朝阳" }, { Code: "211401", Name: "葫芦岛" }, { Code: "210601", Name: "丹东" }, { Code: "220101", Name: "长春" }, { Code: "220201", Name: "吉林" }, { Code: "220301", Name: "四平" }, { Code: "220401", Name: "辽源" }, { Code: "220601", Name: "松原" }, { Code: "222301", Name: "白城" }, { Code: "222401", Name: "延边" }, { Code: "220501", Name: "通化" }, { Code: "230101", Name: "哈尔滨" }, { Code: "230301", Name: "鸡西" }, { Code: "230401", Name: "鹤岗" }, { Code: "230501", Name: "双鸭山" }, { Code: "230701", Name: "伊春" }, { Code: "230801", Name: "佳木斯" }, { Code: "230901", Name: "七台河" }, { Code: "231001", Name: "牡丹江" }, { Code: "232301", Name: "绥化" }, { Code: "230201", Name: "齐齐哈尔" }, { Code: "230601", Name: "大庆" }, { Code: "232601", Name: "黑河" }, { Code: "232700", Name: "大兴安岭" }, { Code: "310100", Name: "上海" }, { Code: "320101", Name: "南京" }, { Code: "320201", Name: "无锡" }, { Code: "320301", Name: "徐州" }, { Code: "320401", Name: "常州" }, { Code: "320501", Name: "苏州" }, { Code: "320600", Name: "南通" }, { Code: "320701", Name: "连云港" }, { Code: "320801", Name: "淮阴" }, { Code: "320901", Name: "盐城" }, { Code: "321001", Name: "扬州" }, { Code: "321101", Name: "镇江" }, { Code: "321102", Name: "泰州" }, { Code: "321103", Name: "宿迁" }, { Code: "330101", Name: "杭州" }, { Code: "330201", Name: "宁波" }, { Code: "330301", Name: "温州" }, { Code: "330401", Name: "嘉兴" }, { Code: "330501", Name: "湖州" }, { Code: "330601", Name: "绍兴" }, { Code: "330701", Name: "金华" }, { Code: "330801", Name: "衢州" }, { Code: "330901", Name: "舟山" }, { Code: "332501", Name: "丽水" }, { Code: "332602", Name: "台州" }, { Code: "340101", Name: "合肥" }, { Code: "340201", Name: "芜湖" }, { Code: "340301", Name: "蚌埠" }, { Code: "340401", Name: "淮南" }, { Code: "340501", Name: "马鞍山" }, { Code: "340601", Name: "淮北" }, { Code: "340701", Name: "铜陵" }, { Code: "340801", Name: "安庆" }, { Code: "341001", Name: "黄山市" }, { Code: "342101", Name: "阜阳" }, { Code: "342201", Name: "宿州" }, { Code: "342301", Name: "滁州" }, { Code: "342401", Name: "六安" }, { Code: "342501", Name: "宣城" }, { Code: "342601", Name: "巢湖" }, { Code: "342901", Name: "池州" }, { Code: "350101", Name: "福州" }, { Code: "350201", Name: "厦门" }, { Code: "350301", Name: "莆田" }, { Code: "350401", Name: "三明" }, { Code: "350501", Name: "泉州" }, { Code: "350601", Name: "漳州" }, { Code: "352101", Name: "南平" }, { Code: "352201", Name: "宁德" }, { Code: "352601", Name: "龙岩" }, { Code: "622602", Name: "陇南" }, { Code: "622603", Name: "庆阳" }, { Code: "360101", Name: "南昌" }, { Code: "360201", Name: "景德镇" }, { Code: "362101", Name: "赣州" }, { Code: "360301", Name: "萍乡" }, { Code: "360401", Name: "九江" }, { Code: "360501", Name: "新余" }, { Code: "360601", Name: "鹰潭" }, { Code: "362201", Name: "宜春" }, { Code: "362301", Name: "上饶" }, { Code: "362401", Name: "吉安" }, { Code: "370101", Name: "济南" }, { Code: "370201", Name: "青岛" }, { Code: "370301", Name: "淄博" }, { Code: "370401", Name: "枣庄" }, { Code: "370501", Name: "东营" }, { Code: "370601", Name: "烟台" }, { Code: "370701", Name: "潍坊" }, { Code: "370801", Name: "济宁" }, { Code: "370901", Name: "泰安" }, { Code: "371001", Name: "威海" }, { Code: "371100", Name: "日照" }, { Code: "372301", Name: "滨州" }, { Code: "372401", Name: "德州" }, { Code: "372501", Name: "聊城" }, { Code: "372801", Name: "临沂" }, { Code: "372901", Name: "菏泽" }, { Code: "372902", Name: "莱芜" }, { Code: "410101", Name: "郑州" }, { Code: "410201", Name: "开封" }, { Code: "410301", Name: "洛阳" }, { Code: "410401", Name: "平顶山" }, { Code: "410501", Name: "安阳" }, { Code: "410601", Name: "鹤壁" }, { Code: "410701", Name: "新乡" }, { Code: "410801", Name: "焦作" }, { Code: "410901", Name: "濮阳" }, { Code: "411001", Name: "许昌" }, { Code: "411101", Name: "漯河" }, { Code: "411201", Name: "三门峡" }, { Code: "412301", Name: "商丘" }, { Code: "412701", Name: "周口" }, { Code: "412801", Name: "驻马店" }, { Code: "412901", Name: "南阳" }, { Code: "413001", Name: "信阳" }, { Code: "420101", Name: "武汉" }, { Code: "420201", Name: "黄石" }, { Code: "420301", Name: "十堰" }, { Code: "420400", Name: "随州" }, { Code: "420501", Name: "宜昌" }, { Code: "420601", Name: "襄樊" }, { Code: "420701", Name: "鄂州" }, { Code: "420801", Name: "荆门" }, { Code: "422103", Name: "黄冈" }, { Code: "422201", Name: "孝感" }, { Code: "422301", Name: "咸宁" }, { Code: "422421", Name: "荆州" }, { Code: "422801", Name: "恩施" }, { Code: "430101", Name: "长沙" }, { Code: "430401", Name: "衡阳" }, { Code: "430501", Name: "邵阳" }, { Code: "432801", Name: "郴州" }, { Code: "432901", Name: "永州" }, { Code: "430801", Name: "韶山" }, { Code: "430802", Name: "张家界" }, { Code: "433001", Name: "怀化" }, { Code: "433101", Name: "吉首" }, { Code: "430201", Name: "株洲" }, { Code: "430301", Name: "湘潭" }, { Code: "430601", Name: "岳阳" }, { Code: "430701", Name: "常德" }, { Code: "432301", Name: "益阳" }, { Code: "432501", Name: "娄底" }, { Code: "440101", Name: "广州" }, { Code: "440601", Name: "佛山" }, { Code: "440301", Name: "深圳" }, { Code: "441501", Name: "汕尾" }, { Code: "441301", Name: "惠州" }, { Code: "441601", Name: "河源" }, { Code: "441801", Name: "清远" }, { Code: "441901", Name: "东莞" }, { Code: "440401", Name: "珠海" }, { Code: "440701", Name: "江门" }, { Code: "441201", Name: "肇庆" }, { Code: "442001", Name: "中山" }, { Code: "440801", Name: "湛江" }, { Code: "440901", Name: "茂名" }, { Code: "440201", Name: "韶关" }, { Code: "440501", Name: "汕头" }, { Code: "441401", Name: "梅州" }, { Code: "441701", Name: "阳江" }, { Code: "441702", Name: "潮州" }, { Code: "441703", Name: "顺德" }, { Code: "441704", Name: "揭阳" }, { Code: "441705", Name: "云浮" }, { Code: "450101", Name: "南宁" }, { Code: "450401", Name: "梧州" }, { Code: "452501", Name: "玉林" }, { Code: "450301", Name: "桂林" }, { Code: "452601", Name: "百色" }, { Code: "452701", Name: "河池" }, { Code: "452802", Name: "钦州" }, { Code: "450201", Name: "柳州" }, { Code: "450501", Name: "北海" }, { Code: "450502", Name: "防城港" }, { Code: "450503", Name: "贵港" }, { Code: "450504", Name: "贺州" }, { Code: "460100", Name: "海口" }, { Code: "460200", Name: "三亚" }, { Code: "460300", Name: "西沙群岛" }, { Code: "510101", Name: "成都" }, { Code: "513321", Name: "眉山" }, { Code: "513101", Name: "雅安" }, { Code: "513229", Name: "峨嵋山" }, { Code: "510301", Name: "自贡" }, { Code: "500100", Name: "重庆" }, { Code: "500102", Name: "万州" }, { Code: "500103", Name: "涪陵" }, { Code: "512901", Name: "南充" }, { Code: "510501", Name: "泸州" }, { Code: "510601", Name: "德阳" }, { Code: "510701", Name: "绵阳" }, { Code: "510901", Name: "遂宁" }, { Code: "511001", Name: "内江" }, { Code: "511101", Name: "乐山" }, { Code: "512501", Name: "宜宾" }, { Code: "510801", Name: "广元" }, { Code: "513021", Name: "达州" }, { Code: "513401", Name: "资阳" }, { Code: "510401", Name: "攀枝花" }, { Code: "510402", Name: "阿坝" }, { Code: "510403", Name: "甘孜" }, { Code: "510404", Name: "凉山" }, { Code: "510405", Name: "广安" }, { Code: "510406", Name: "巴中" }, { Code: "500239", Name: "黔江" }, { Code: "520101", Name: "贵阳" }, { Code: "520200", Name: "六盘水" }, { Code: "522201", Name: "铜仁" }, { Code: "522501", Name: "安顺" }, { Code: "522601", Name: "凯里" }, { Code: "522701", Name: "都匀" }, { Code: "522301", Name: "兴义" }, { Code: "522421", Name: "毕节" }, { Code: "522101", Name: "遵义" }, { Code: "530101", Name: "昆明" }, { Code: "530201", Name: "德宏" }, { Code: "532201", Name: "曲靖" }, { Code: "532301", Name: "楚雄" }, { Code: "532401", Name: "玉溪" }, { Code: "532501", Name: "红河" }, { Code: "532621", Name: "文山" }, { Code: "532721", Name: "思茅" }, { Code: "532101", Name: "昭通" }, { Code: "532821", Name: "西双版纳" }, { Code: "532901", Name: "大理" }, { Code: "533001", Name: "保山" }, { Code: "533121", Name: "怒江" }, { Code: "533221", Name: "丽江" }, { Code: "533321", Name: "迪庆" }, { Code: "533521", Name: "临沧" }, { Code: "540101", Name: "拉萨" }, { Code: "542121", Name: "昌都" }, { Code: "542221", Name: "山南" }, { Code: "542301", Name: "日喀则" }, { Code: "542421", Name: "那曲" }, { Code: "542523", Name: "阿里" }, { Code: "542621", Name: "林芝" }, { Code: "610101", Name: "西安" }, { Code: "610201", Name: "铜川" }, { Code: "610301", Name: "宝鸡" }, { Code: "610401", Name: "咸阳" }, { Code: "612101", Name: "渭南" }, { Code: "612301", Name: "汉中" }, { Code: "612401", Name: "安康" }, { Code: "612501", Name: "商洛" }, { Code: "612601", Name: "延安" }, { Code: "612701", Name: "榆林" }, { Code: "620101", Name: "兰州" }, { Code: "620401", Name: "白银" }, { Code: "620301", Name: "金昌" }, { Code: "620501", Name: "天水" }, { Code: "622201", Name: "张掖" }, { Code: "622301", Name: "武威" }, { Code: "622421", Name: "定西" }, { Code: "622701", Name: "平凉" }, { Code: "622901", Name: "临夏" }, { Code: "620201", Name: "嘉峪关" }, { Code: "622102", Name: "酒泉" }, { Code: "630100", Name: "西宁" }, { Code: "632121", Name: "果洛" }, { Code: "632221", Name: "海西" }, { Code: "632321", Name: "格尔木" }, { Code: "632521", Name: "海东" }, { Code: "632621", Name: "海北" }, { Code: "632721", Name: "玉树" }, { Code: "632802", Name: "黄南" }, { Code: "640101", Name: "银川" }, { Code: "640201", Name: "石嘴山" }, { Code: "642101", Name: "吴忠" }, { Code: "642221", Name: "固原" }, { Code: "650101", Name: "乌鲁木齐" }, { Code: "650201", Name: "克拉玛依" }, { Code: "652101", Name: "吐鲁番" }, { Code: "652201", Name: "哈密" }, { Code: "652301", Name: "昌吉" }, { Code: "652701", Name: "博乐" }, { Code: "652801", Name: "库尔勒" }, { Code: "652901", Name: "阿克苏" }, { Code: "653001", Name: "克州" }, { Code: "653101", Name: "喀什" }, { Code: "654101", Name: "伊犁" }, { Code: "655001", Name: "石河子" }, { Code: "655002", Name: "塔城" }, { Code: "655003", Name: "阿勒泰" }, { Code: "710001", Name: "台北" }, { Code: "211001", Name: "辽阳" }, { Code: "653201", Name: "和田" }, { Code: "820000", Name: "澳门" }, { Code: "810000", Name: "香港" }, { Code: "130101", Name: "河北" }, { Code: "140101", Name: "山西" }, { Code: "150101", Name: "内蒙古" }, { Code: "210101", Name: "辽宁" }, { Code: "220101", Name: "吉林" }, { Code: "230101", Name: "黑龙江" }, { Code: "320101", Name: "江苏" }, { Code: "330101", Name: "浙江" }, { Code: "340101", Name: "安徽" }, { Code: "350101", Name: "福建" }, { Code: "360101", Name: "江西" }, { Code: "370101", Name: "山东" }, { Code: "410101", Name: "河南" }, { Code: "420101", Name: "湖北" }, { Code: "430101", Name: "湖南" }, { Code: "440101", Name: "广东" }, { Code: "450101", Name: "广西" }, { Code: "460100", Name: "海南" }, { Code: "510101", Name: "四川" }, { Code: "520101", Name: "贵州" }, { Code: "530101", Name: "云南" }, { Code: "540101", Name: "西藏" }, { Code: "610101", Name: "陕西" }, { Code: "620101", Name: "甘肃" }, { Code: "630100", Name: "青海" }, { Code: "640101", Name: "宁夏" }, { Code: "650101", Name: "新疆" }, { Code: "710001", Name: "台湾"}];

    for (var i = 0; i < citys.length; i++) {
        if (cityName.indexOf(citys[i].Name) >= 0) return citys[i].Code;
    }

    return "";
}

//Cookie日期修正函数 function FixCookieDate(date)
function FixCookieDate(date) {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0) date.setTime(date.getTime() - skew);
}

//设置Cookie函数 function SetCookie(name,value,expires,path,domain,secure)
function SetCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

//设置Cookie相应名值对中值的函数 function getCookieVal(offset)
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

//设置Cookie函数 function GetCookie(name)
function GetCookie(name) {
    var arg = name + '=';
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    var flag = ''
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) flag = getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return flag;
}

//快递计算 shopEx
function getval(expval) {
    if (eval(expval) > 0.000001) {
        return 1;
    } else if (eval(expval) > -0.000001 && eval(expval) < 0.000001) {
        return 1 / 2;
    } else {
        return 0;
    }
}

function getceil(expval) {
    if (eval(expval) > 0) {
        return Math.ceil(eval(expval) - 0.000001);
    } else {
        return 0;
    }
}

function countexp() {
    var bds = $('#<%= dlg_expressions.ClientID %>').val();

    if (bds == '') {
        alert("请输入配送公式");
        return;
    }

    var re = new RegExp("/^[^\]\[\}\{\)\(0-9WwPp\+\-\/\*]+$/");
    if (re.test(bds)) {
        alert("公式中含有非法字符");
        return;
    }

    var price = $('#orderprice').val();
    var weight = $('#<%= weight.ClientID %>').val();
    var str;
    str = bds.replace(/(\[)/g, "getceil(");
    str = str.replace(/(\])/g, ")");
    str = str.replace(/(\{)/g, "getval(");
    str = str.replace(/(\})/g, ")");
    str = str.replace(/(W)/g, weight);
    str = str.replace(/(w)/g, weight);
    str = str.replace(/(P)/g, price);
    str = str.replace(/(p)/g, price);

    try {
        eval(str);
    }
    catch (e) {
        alert("公式格式不正确");
        return;
    }

    return Math.floor(eval(str) * 100 + 0.01) / 100;
}